/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.etsf01.aesp.gui;

import com.sun.org.apache.xalan.internal.xsltc.compiler.util.FilterGenerator;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.text.DecimalFormat;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.*;
import javax.swing.table.DefaultTableModel;
import se.etsf01.aesp.*;
import se.etsf01.aesp.algo.*;

/**
 *
 * @author tugger
 */
public class ReportWindow extends javax.swing.JFrame {

    private EstimationResult result;
    private Project proj;
    private DecimalFormat df = new DecimalFormat();

    /**
     * Creates new form ReportWindow
     */
    public ReportWindow(Project proj, EstimationResult result) {
        this.result = result;
        this.proj = proj;
        if(result.succeeded()) {
            initComponents();
            setPosition();
            postInit();
            setVisible(true);
        } else {
            JOptionPane.showMessageDialog(null, "No estimation could be calculated. \n Please consider your similarity threshold.");
        }
        
    }

    private void postInit() {
        df.applyPattern("0.00");
        for (int i = 0; i < result.getAdaptiationSource().size(); i++) {
            tModel.addRow(new Object[]{i + 1, result.getAdaptiationSource().get(i).getIdentifier(), df.format(result.getAdaptiationSource().get(i).getSimilarity()*100.0) + "%"});
        }
        
        sources.setText("Estimated from the following " + Integer.toString(result.getAdaptiationSource().size()) + " sources:");
        df.applyPattern("#.##");
        effortLabel.setText("<html>Estimated effort:<br>" + df.format(result.getEstimatedEffort().toPersonMonths()) + " person-months</html>");

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        sources = new javax.swing.JLabel();
        effortLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tModel = new DefaultTableModel();
        projectTable = new javax.swing.JTable(tModel);
        unitComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        btnExport = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Estimation Report");

        sources.setText("sources");

        effortLabel.setText("Effort");

        projectTable.setEnabled(false);
        tModel.addColumn("#");
        tModel.addColumn("Project Name");
        tModel.addColumn("Similarity");
        jScrollPane1.setViewportView(projectTable);

        unitComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Person years", "Person months", "Person days", "Person hours" }));
        unitComboBox.setSelectedIndex(1);
        unitComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                unitComboBoxActionPerformed(evt);
            }
        });

        jLabel1.setText("View result in:");

        btnExport.setText("Export");
        btnExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(unitComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(3, 3, 3)
                                .addComponent(effortLabel))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnExport))))
                    .addComponent(sources, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(sources, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(unitComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(72, 72, 72)
                        .addComponent(effortLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
                        .addComponent(btnExport))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 14, Short.MAX_VALUE)))
                .addContainerGap(12, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        effortLabel.getAccessibleContext().setAccessibleName("effort");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void unitComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unitComboBoxActionPerformed
        Object value = unitComboBox.getSelectedIndex();
        switch ((Integer) value) {
            case 0:
                df.applyPattern("#.###");
                effortLabel.setText("<html>Estimated effort:<br>" + df.format(result.getEstimatedEffort().toPersonYear()) + " person-years</html>");
                break;
            case 1:
                df.applyPattern("#.##");
                effortLabel.setText("<html>Estimated effort:<br>" + df.format(result.getEstimatedEffort().toPersonMonths()) + " person-months</html>");
                break;
            case 2:
                df.applyPattern("#.##");
                effortLabel.setText("<html>Estimated effort:<br>" + df.format(result.getEstimatedEffort().toPersonDays()) + " person-days</html>");
                break;
            case 3:
                df.applyPattern("#");
                effortLabel.setText("<html>Estimated effort:<br>" + df.format(result.getEstimatedEffort().toPersonHours()) + " person-hours</html>");
        }
    }//GEN-LAST:event_unitComboBoxActionPerformed

    private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportActionPerformed
        JFileChooser choose = new JFileChooser();
        choose.setDialogTitle("Save HTML Report");
        FileFilter ff = new FileFilter() {

            @Override
            public boolean accept(File file) {
                if(file.getAbsolutePath().toLowerCase().endsWith("html"))
                {
                    return true;
                }
                else {
                    return false;
                }
            }

            @Override
            public String getDescription() {
                return "HTML files (*.html)";
            }
        };
        
        choose.setFileFilter(ff);
                
        if(choose.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            String path = choose.getSelectedFile().getAbsolutePath();
            if (path.indexOf('.')==-1) {
                path += ".html";
            }
            
            ExportHTML exporter = new ExportHTML(path, proj, result);
            if(exporter.export()) {
                JOptionPane.showMessageDialog(this, "Successful export!", "Export to HTML", JOptionPane.INFORMATION_MESSAGE);
            }
            else
            {
                JOptionPane.showMessageDialog(this, "Failed to export.", "Export to HTML", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnExportActionPerformed
    
    private void setPosition() {
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

    int w = getSize().width;
    int h = getSize().height;
    
    setLocation((dim.width-w)/2, (dim.height-h)/2);
    }
    /**
     * @param args the command line arguments
     */
    private DefaultTableModel tModel;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExport;
    private javax.swing.JLabel effortLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable projectTable;
    private javax.swing.JLabel sources;
    private javax.swing.JComboBox unitComboBox;
    // End of variables declaration//GEN-END:variables
}
